#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
"""
@File    :   schema.py
@Time    :   2024/02/07 19:34:39
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib
from typing import Any
from django.db import transaction
from ninja import Field
from ninja_schema import ModelSchema, model_validator
from ninja_extra import service_resolver
from ninja_extra.controllers import RouteContext
from ninja_extra.exceptions import APIException

from .models import Article
from app.category.schema import CategorySchema
from app.category.models import ArticleCategory
from core.schemas import CoreModelSchema


class ArticleSchema(ModelSchema):
    cate: CategorySchema
    status: int = Field(..., description="发布状态")

    class Config:
        model = Article
        include = ["id", "title", "content", "cover_img"]


class CreateArticleSchema(CoreModelSchema):
    cate_id: int = Field(..., description="分类id")
    status: int = Field(..., description="发布状态")

    class Config:
        model = Article
        include = ["title", "content", "cover_img"]

    @model_validator("cate_id", mode="before")
    def cate_validate(cls, value_data):
        """
        验证分类id是否存在
        :param value_data: 分类id
        :return: 分类id
        """
        context: RouteContext = service_resolver(RouteContext)
        # 验证分类id是否存在
        if ArticleCategory.objects.filter(
            id=value_data, creator_id=context.request.user.id
        ).exists():
            return value_data
        else:
            raise APIException("分类ID不存在")

    @transaction.atomic
    def create_obj(self, **kwargs: Any):
        context: RouteContext = service_resolver(RouteContext)
        _data = self.dict(exclude_none=True)
        _data["creator"] = context.request.user
        _data["modifier"] = context.request.user.username
        _data.update(kwargs)
        return Article.objects.create(**_data)
    
    @transaction.atomic
    def update(self,instance: Any,**kwargs: Any):
        context: RouteContext = service_resolver(RouteContext)
        _data = self.dict(exclude_none=True)
        _data["modifier"] = context.request.user.username
        _data.update(kwargs)
        for attr, value in _data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance
